#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>
#include "../comm/Util.hpp"
#include "../comm/Log.hpp"

namespace runner_ns
{
    using namespace util_ns;
    using namespace log_ns;
    class Runner
    {
    public:
        Runner()
        {}
        ~Runner()
        {}

        // 对cpu和内存进行设置
        static void SetProcLimit(int _cpu_limit, int _mem_limit)
        {
            // cpu
            struct rlimit _cpu;
            _cpu.rlim_cur = _cpu_limit;
            _cpu.rlim_max =  RLIM_INFINITY;
            setrlimit(RLIMIT_CPU, &_cpu); // RLIMIT_CPU!

            // 内存
            struct rlimit _mem;
            _mem.rlim_cur = _mem_limit * 1024; // 转换成为KB
            _mem.rlim_max = RLIM_INFINITY;
            setrlimit(RLIMIT_AS, &_mem); // RLIMIT_AS!
        } 

        // 运行可执行文件，先有可执行文件 
        // 返回值 > 0: 返回异常错误
        // 返回值 = 0: 运行成功
        // 返回值 < 0: 内部错误
        // 把结果分别给 标准输入、标准输出、标准错误 文件
        static int Run(const std::string &file_name, int cpu_limit, int mem_limit)
        {   
            std::string _excute = PathUtil::Exe(file_name);
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);

            // 子进程可以继承父进程的文件描述符
            // 打开文件
            umask(0);
            int _stdin_fd = open(_stdin.c_str(), O_CREAT|O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT|O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT|O_WRONLY, 0644);
            if(_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(ERROR) << "打开文件失败" << "\n";
                return -1;
            }

            pid_t pid = fork();
            if(pid < 0)
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                LOG(ERROR) << "创建子进程失败" << "\n";
                return -2;
            }
            else if(pid == 0)
            {
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);

                // 资源限制
                SetProcLimit(cpu_limit, mem_limit);

                execl(_excute.c_str(), _excute.c_str(), nullptr);
                exit(1);
            }
            else 
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                int status = 0;
                waitpid(pid, &status, 0);
                LOG(INFO) << "运行成功" << ", info: " << (status & 0x7F) << "\n";
                return status & 0x7F;
            }
        }
    };
}